<template>
  <el-dialog class="operation-popup" :title="dialogTitle + '（' + month + '月）'" :visible="showFurther" @close="closeDialog" :close-on-click-modal="false" width="70%">
    <div class="chartDiv" id="chartDiv">
      <div id="m_CHARTS"></div>
    </div>
  </el-dialog>
</template>

<script>
// import dayjs from 'dayjs';
import { getProgramRightsDeviation } from '../../../api/deviation';
var echarts = require('echarts');

export default {
  props: {
    selectTime: {
      type: String,
      default: '',
    },
    dialogType: {
      type: Number,
      default: 1,
    },
  },

  data() {
    return {
      option: {},
      month: '',
      myChart: null,
      colorList: ['#9cbd8e', '#bcc56b', '#7a8ac0', '#bf92c4', '#0e2741', '#308588', '#cE5079'],
      dataList: [
        {
          name: '',
          children: [],
        },
      ],
      showFurther: false,
    };
  },

  methods: {
    // 关闭
    closeDialog() {
      this.showFurther = false;
      let x = echarts.init(document.getElementById('m_CHARTS'));
      x.clear();
      this.dataList[0].children = [];
    },
    async getList(row) {
      if (!row.primaryKey || row.primaryKey.startsWith('self')) {
        return false
      }

      this.month = row.planMonth;
      let res = {};
      let params = {};
      if (this.dialogType == 1) {
        params = {
          primaryKey: row.primaryKey,
          planMonth: row.planMonth,
          type: 1,
        };
      } else if (this.dialogType == 2) {
        params = {
          primaryKey: row.primaryKey,
          planMonth: row.planMonth,
          type: 2,
        };
      } else if (this.dialogType == 3) {
        params = {
          primaryKey: row.primaryKey,
          planMonth: row.planMonth,
          type: 3,
        };
      }
      res = await getProgramRightsDeviation({ ...params });
      this.setDataList(res);
      this.load();
    },
    load() {
      this.comparison();
      this.setOption();
      this.myChart = echarts.init(document.getElementById('m_CHARTS'));
      this.option && this.myChart.setOption(this.option);
      console.log('option', this.option);
    },
    //set图的值
    setDataList(res) {
      this.dataList[0].name = res.dataName + '\n' + '¥' + this.fmoney(Number(res.planPrice)) + '\n' + this.fmoney(Number(res.forecastPrice)) + '\n' + res.deviationRatio;
      // 收入
      let income = '/businessPlan/businessManagementOperation/planRevenue' + location.search + '&month=' + this.month;
      let disburse = '/businessPlan/businessManagementOperation/planExpenditure' + location.search + '&month=' + this.month;
      res.childList.forEach((item, index) => {
        this.dataList[0].children.push({
          name: item.dataName + '\n' + '¥' + this.fmoney(Number(item.planPrice)) + '\n' + this.fmoney(Number(item.forecastPrice)) + '\n' + item.deviationRatio,
          value: Number(item.planPrice),
          children: [],
          // this.dialogType
          link: `${window.location.origin}${this.dialogType == 3 ? disburse : income}`,
          label: {
            fontSize: 12,
            fontWeight: 'bold',
            fontFamily: 'Arial',
          },
          itemStyle: {
            color: this.colorList[index],
          },
        });
        item.childList.forEach((item2, index2) => {
          this.dataList[0].children[index].children.push({
            name: item2.dataName + '\n' + '¥' + this.fmoney(Number(item2.planPrice)) + '\n' + this.fmoney(Number(item2.forecastPrice)) + '\n' + item2.deviationRatio,
            value: Number(item2.planPrice),
            label: {
              fontSize: 12,
              fontWeight: 'bold',
              fontFamily: 'Arial',
            },
            itemStyle: {
              color: this.colorList[index2],
            },
          });
        });
      });
    },
    //设置option
    setOption() {
      this.option = {
        title: {
          textStyle: {
            fontSize: 14,
            align: 'center',
          },
          subtextStyle: {
            align: 'center',
          },
        },
        series: {
          type: 'sunburst',
          data: this.dataList,
          sort: undefined,
          nodeClick: 'link', // 取消点击
          emphasis: {
            focus: 'ancestor',
          },
          levels: [
            {},
            {
              r0: '15%',
              r: '35%',
              itemStyle: {
                borderWidth: 2,
              },
              label: {
                rotate: 'tangential',
              },
            },
            {
              r0: '35%',
              r: '70%',
              label: {
                align: 'center',
                fontSize: 12,
              },
              itemStyle: {},
            },
            {
              r0: '70%',
              r: '72%',
              label: {
                position: 'outside',
                padding: 3,
                silent: false,
              },
              itemStyle: {
                borderWidth: 3,
              },
            },
          ],
        },
      };
    },
    //初始化渲染
    comparison() {
      setTimeout(() => {
        this.chartssize(document.getElementById('chartDiv'), document.getElementById('m_CHARTS'));
        this.myChart.resize();
        window.addEventListener('resize', res => {
          this.chartssize(document.getElementById('chartDiv'), document.getElementById('m_CHARTS'));
          this.myChart.resize();
        });
      }, 1000);
    },
    //设置echarts宽高为父容器宽高
    chartssize(container, charts) {
      if (!container && !charts) return;
      function getStyle(el, name) {
        if (window.getComputedStyle) {
          return window.getComputedStyle(el, null);
        } else {
          return el.currentStyle;
        }
      }
      let obj = getStyle(container);
      charts.style.height = obj.height;
    },
    //千分制
    fmoney(s, n) {
      n = n > 0 && n <= 20 ? n : 2;
      s = parseFloat((s + '').replace(/[^\d\.-]/g, '')).toFixed(n) + '';
      var l = s.split('.')[0].split('').reverse(),
        r = s.split('.')[1],
        t = '';
      for (let i = 0; i < l.length; i++) {
        t += l[i] + ((i + 1) % 3 == 0 && i + 1 != l.length ? ',' : '');
      }
      return t.split('').reverse().join('') + '.' + r;
    },
  },
  computed: {
    dialogTitle() {
      let title = '';
      let dialogType = this.dialogType;
      // dialogType  1：收入权责偏差弹层，2：收入现金流偏差弹层， 3：支出现金流偏差弹层
      if (dialogType == 1 || dialogType == 2 || dialogType == 3) {
        title = '年累计收入偏差分析';
      }
      return title;
    }
  },
};
</script>
<style lang="scss">
.operation-popup {
  .el-dialog__header {
    background: #444444;
  }
}
.chartDiv {
  width: 800px;
  height: 700px;
  margin: 0 auto;
}
.box-card {
  height: 100%;
  width: 100%;
}
</style>
